import React from 'react'
import { Button, Modal, Table,Form,Input } from 'antd'
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { useState, useEffect,useRef,useContext } from 'react'
import axios from 'axios'
const EditableContext = React.createContext(null);
// import { Switch } from 'react-router'
const { confirm } = Modal;
export default function NewsCategory() {
    const [dataSource, setdataSource] = useState([])

    // 获取新闻分类列表
    useEffect(() => {
        axios.get("/categories").then(res => {
            const list = res.data;
            setdataSource(list);
        })
    }, [])

    // 删除消息框
    const confirmMethods = (item) => {
        confirm({
            title: '您确定要删除吗？',
            icon: <ExclamationCircleOutlined />,

            onOk() {
                deleteMethod(item);
            },

            onCancel() {

            },
        });
    }
    //删除菜单项
    const deleteMethod = (item) => {
        const list = dataSource.filter(data => data.id === item.id);
        setdataSource(list);
        axios.delete(`/categories/${item.id}`)
    }

    // 当单元格内容失去焦点时触发
    const handleSave=(record)=>{
        console.log(record);
        // 更新页面数据
        setdataSource(dataSource.map(item=>{
            if(item.id===record.id){
                return {
                    id:item.id,
                    title:record.title,
                    value:record.title
                }
            }
            return item
        }))

        // 更新后台数据
        axios.patch(`/categories/${record.id}`,{
            title:record.title,
            value:record.title
        })
    }

    const columns = [
        {
            // 列表标题
            title: 'ID',
            //   列表内容名称
            dataIndex: 'id',
            render: (id) => {
                return <b>{id}</b>
            }
        },
        {
            title: '栏目名称',
            dataIndex: 'title',
            onCell: (record) => ({
                record,
                editable: true,
                dataIndex: 'title',
                title: '栏目名称',
                handleSave,
              }),
        },
        {
            title: '操作',
            render: (item) => {
                return (
                    <div>
                        {/* 删除按钮 */}
                        <Button danger shape="circle" icon={<DeleteOutlined />}
                            onClick={() => confirmMethods(item)}></Button>
                    </div>
                )
            }
        }
    ];

    // 插件数据行
    const EditableRow = ({ index, ...props }) => {
        const [form] = Form.useForm();
        return (
            <Form form={form} component={false}>
                <EditableContext.Provider value={form}>
                    <tr {...props} />
                </EditableContext.Provider>
            </Form>
        );
    };

    // 插件数据单元格
    const EditableCell = ({
        title,
        editable,
        children,
        dataIndex,
        record,
        handleSave,
        ...restProps
      }) => {
        const [editing, setEditing] = useState(false);
        const inputRef = useRef(null);
        const form = useContext(EditableContext);
        useEffect(() => {
          if (editing) {
            inputRef.current.focus();
          }
        }, [editing]);
      
        const toggleEdit = () => {
          setEditing(!editing);
          form.setFieldsValue({
            [dataIndex]: record[dataIndex],
          });
        };
      
        const save = async () => {
          try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({ ...record, ...values });
          } catch (errInfo) {
            console.log('Save failed:', errInfo);
          }
        };
      
        let childNode = children;
      
        if (editable) {
          childNode = editing ? (
            <Form.Item
              style={{
                margin: 0,
              }}
              name={dataIndex}
              rules={[
                {
                  required: true,
                  message: `${title} is required.`,
                },
              ]}
            >
              <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
          ) : (
            <div
              className="editable-cell-value-wrap"
              style={{
                paddingRight: 24,
              }}
              onClick={toggleEdit}
            >
              {children}
            </div>
          );
        }
      
        return <td {...restProps}>{childNode}</td>;
      };

    return (
        <div>
            <Table dataSource={dataSource} columns={columns}
                rowKey={(item) => item.id}
                components={{
                    body: {
                        row: EditableRow,
                        cell: EditableCell,
                    },
                }}
                pagination={{
                    pageSize: 5
                }} />
        </div>
    )
}
